# -*- coding:utf-8 -*-

from apscheduler.scheduler import Scheduler
from subprocess import Popen, PIPE
from threading import Thread
from Queue import Queue
from utils import DbSession
import time
import urllib2
import logging

logging.basicConfig(level = logging.WARN)
logging.getLogger(__name__)

def pingtask(desthost, count):
    handler = Popen("ping -c %d -w5 %s" % (count, desthost), shell = True, stdout = PIPE, stderr = PIPE)
    retcode = handler.wait()
    if retcode == 0:
        print(desthost, "is ok", time.time())
    else:
        print(desthost, "is not ok", handler.stdout.read(), time.time())

def httpgettask(url):
    try:
        response = urllib2.urlopen(url, timeout = 10)
        print dir(response)
        if response.getcode() != 200:
            print(url,"get failed")
        else:
            print(url,"get ok")
    except:
        print(url, "get failed")

def addtask():
    with DbSession() as session:
        sql ="""insert into m_services(service_type, service_descr, service_status,check_interval) values('HTTP','{"url":"http://www.wwouwwdwww.com","timeout":10}', 'NEW', 15)"""
        session.update(sql)
        return session.selectone("select max(id) from m_services")
def deletehttptask():
    with DbSession() as session:
        sql ="""delete from m_services where service_type = 'HTTP'"""
        session.update(sql)
    
def printServices():
    with DbSession() as session:
        sql = """select * from m_services"""
        srv = session.selectall(sql)
        for data in srv:
            print data

def onetimetask():
    print "this is a one time task", time.time()

class CleanerThread(Thread):
    def __init__(self, scheduler):
        super(CleanerThread, self).__init__()
        self.sched = scheduler
        self.canceltasks = Queue(10)

    def init(self, func, *args):
        return self.sched.add_interval_job(func, args=args, seconds = 2)

    def canceltask(self, taskins):
        self.canceltasks.put_nowait(taskins)

    def run(self):
        while 1:
            taskins = self.canceltasks.get()
            print(taskins)
            self.sched.unschedule_job(taskins)
            print(taskins, "already canceled")

if __name__ == '__main__':
    """sched = Scheduler()
    ips = ["203.169.242.24","203.169.242.35","203.169.242.39"]
    pingtasks = []

    sched.start()        

    cleaner = CleanerThread(sched)
    cleaner.start()

    for ip in ips:
        pingtasks.append(cleaner.init(pingtask, ip, 5))

    print("scheduler started!")
    # sched.add_interval_job(httpgettask, args=["http://www.google.com"], minutes = 1)
    # sched.add_interval_job(httpgettask, args=["http://www.google.com/asdf"], minutes = 1)
    # sched.add_interval_job(httpgettask, args=["http://mail.126.com"], minutes = 1)
    # etime = datetime.now() + timedelta(seconds = 20)
    # sched.add_date_job(onetimetask, etime)
    time.sleep(20)
    for x in pingtasks:
        cleaner.canceltask(x)

    print(dir(pingtasks[0]))
    cleaner.join()"""
    #addtask()
    #deletehttptask()
    printServices()
